const regeneratorRuntime = require("../../utils/runtime.js")
const login = require('../../utils/utils.js')
const {
  _post,
  _get,
  _request
} = require('../../utils/request.js')

import Notify from '/@vant/weapp/notify/notify'

// 计算时间差
function calcDate(dateTimeStamp, minute = 60000, hour = 3600000, day = 86400000) {
  var result = ''
  var now = new Date().getTime()
  var diffValue = now - dateTimeStamp
  if (diffValue < 0) {
    return result = "刚刚"
  }
  var dayC = diffValue / day
  var hourC = diffValue / hour
  var minC = diffValue / minute
  if (parseInt(dayC) > 30) {
    result = "" + this.$format(dateTimeStamp, "yyyy-MM-dd")
  } else if (parseInt(dayC) > 1) {
    result = "" + parseInt(dayC) + "天前"
  } else if (parseInt(dayC) == 1) {
    result = "昨天"
  } else if (hourC >= 1) {
    result = "" + parseInt(hourC) + "小时前"
  } else if (minC >= 5) {
    result = "" + parseInt(minC) + "分钟前"
  } else
    result = "刚刚"
  return result
}
Page({
  data: {
    articleList: {},
    isFirstLoad: true,
    collectionTags: [],
    selectedTag: [],
    sortedList: null
  },

  handleCellClick(e) {
    wx.navigateTo({
      url: '/pages/article/article?id=' + e.currentTarget.dataset.id,
    })
  },

  async onLoad() {
    await this.getHistory()
  },


  async getHistory() {
    let historyData = wx.getStorageSync('history')
    if (typeof historyData !== 'string') {
      historyData = ''
    }
    let history = JSON.parse(historyData || '{}'),
      list = []

    for (let key in history) {
      list.push(history[key])
    }

    list = list.sort((a, b) => {
      return b.add_time - a.add_time
    })

    let articleList = {
        list
      },
      collectionTags = []
    if (articleList.list && articleList.list instanceof Array) {
      for (let i = 0; i < articleList.list.length; i++) {
        articleList['list'][i]['add_time'] = calcDate(new Date(articleList['list'][i]['add_time']).valueOf())
        if (articleList['list'][i]['labels'] && articleList['list'][i]['labels'] instanceof Array) {
          collectionTags = collectionTags.concat(articleList['list'][i]['labels'])
        }
      }
    }
    this.setData({
      articleList,
      isFirstLoad: false,
      collectionTags: [...new Set(collectionTags)]
    })

  },

  handleGetSelectedTag(e) {
    let tags = e.detail.tags,
      list = this.data.articleList.list,
      sorted = {},
      isEmpty = true
    for (let i = 0; i < list.length; i++) {
      if (list[i]['labels'] && list[i]['labels'] instanceof Array) {
        for (let k in tags) {
          if (list[i]['labels'].includes(k) && tags[k]) {
            sorted[list[i]['id']] = list[i]
            isEmpty = false
          }
        }
      }
    }
    this.setData({
      selectedTag: e.detail.tags,
      sortedList: isEmpty ? [] : sorted
    })
  },

  async handleRemoveCollection(e) {
    let history = JSON.parse(wx.getStorageSync('history') || '{}')

    if (history[e.currentTarget.dataset.id + '']) {
      delete history[e.currentTarget.dataset.id + '']
    }

    wx.setStorageSync('history', JSON.stringify(history))
    Notify({
      type: 'success',
      message: '已移除'
    })

    await this.getHistory()
  },

  async onShow() {
    if (this.data.articleList.list) {
      await this.getHistory()
    }
  }
})